package com.hmdp.utils;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.Base64;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;


/**
 * @Author lxh
 * @Date 2022/8/1
 * @Date 20:31
 * @Version 1.0
 */
@Slf4j
public class JwtUtil{

    public static  <T> String jwtEncode(T t,long expire) throws JSONException {
        //第一部分头部
        JSONObject jwtHeader = new JSONObject();
        jwtHeader.put("jwt","HS512");

        //第二部分负载
        JwtPayload<T> body = new JwtPayload<>(t, LocalDateTime.now().getSecond()+expire);
        String jwtPayload = JSONUtil.toJsonStr(body);
        //对数据实现base64Encode()
        String header = Base64.getEncoder().encodeToString(jwtHeader.toString().getBytes());
        String payload = Base64.getEncoder().encodeToString(jwtPayload.getBytes());
        //md5 是单向加密算法
        //签名 后面加秘钥（盐值）
        String signKey="myKtKey";
        String sign = DigestUtil.md5Hex(jwtPayload.toString()+signKey);
        String jwt=header+"."+payload+"."+sign;
        return jwt;
    }
    public static <T> T jwtDecode(String jwt,Class<T>  tClass) throws UnsupportedEncodingException {
        String payLoadStr=new String(Base64.getDecoder().decode(jwt.split("\\.")[1].getBytes()),"UTF-8");
        JwtPayload<JSONObject> body = JSONUtil.toBean(payLoadStr, JwtPayload.class);
        long expireTime = body.getExpire();
        if(LocalDateTime.now().getSecond()>expireTime){
            log.debug("已过期");
            return null;
        }
        log.info("还剩："+(expireTime-LocalDateTime.now().getSecond())+"秒过期");
        String jwtSign=jwt.split("\\.")[2];
        String signKey="myKtKey";
        if(DigestUtil.md5Hex(payLoadStr+signKey).equals(jwtSign)){
            JSONObject data =body.getData();
            return JSONUtil.toBean(data,tClass);
        }
        return null;
    }
    public static long getJwtExpire(String jwt) throws UnsupportedEncodingException {
        String payLoadStr=new String(Base64.getDecoder().decode(jwt.split("\\.")[1].getBytes()),"UTF-8");
        JwtPayload<JSONObject> body = JSONUtil.toBean(payLoadStr, JwtPayload.class);
        long expireTime = body.getExpire();
        //判断jwt是否已被作废(退出登陆)

        if(LocalDateTime.now().getSecond()>expireTime){
            log.debug("已过期");
            return 0L;
        }else{
            return expireTime-LocalDateTime.now().getSecond();
        }
    }
}
